package com.whccb.apps.office.document.event;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.actionsoft.bpms.bo.engine.BO;
import com.actionsoft.bpms.bpmn.engine.core.delegate.ProcessExecutionContext;
import com.actionsoft.bpms.bpmn.engine.listener.ExecuteListener;
import com.actionsoft.bpms.org.cache.TeamCache;
import com.actionsoft.bpms.org.model.TeamModel;
import com.actionsoft.sdk.local.SDK;

public class ModifyTOAndCCAfterTaskComplateEvent extends ExecuteListener {

	public String getDescription() {
		return "根据FILETO和FILECC更新TOID和CCID,TOID和CCID为公文模版书签对应值";
	}

	public String getProvider() {
		return "ActionSoft";
	}

	public String getVersion() {
		return "AWS 6.0";
	}

	public void execute(ProcessExecutionContext pec) throws Exception {
		Map<String, Object> paramMap = SDK.getProcessAPI().getVariables(
				pec.getProcessInstance().getId());
		if (paramMap != null && !paramMap.isEmpty()) {
			String boName = paramMap.get("BONAME") != null ? paramMap.get(
					"BONAME").toString() : "";
			BO bo = SDK.getBOAPI().getByProcess(boName,
					pec.getProcessInstance().getId());
			if (bo != null) {
				if (bo.getString("FILETO") != null) {
					String toid = "";
					String fileToStr = bo.getString("FILETO");
					if (StringUtils.isNotEmpty(fileToStr)) {
						String[] fileTos = fileToStr.split(",");
						if (fileTos != null && fileTos.length > 0) {
							for (String fileTo : fileTos) {
								if (StringUtils.isNotEmpty(fileTo)) {
									// 根据团队ID查询团队名称
									TeamModel team = TeamCache.getModel(fileTo);
									if (team != null
											&& StringUtils.isNotEmpty(team
													.getName())) {
										toid = toid + team.getName() + ",";
									}
								}
							}
						}
					}
					if (StringUtils.isNotEmpty(toid)) {
						toid = toid.substring(0, toid.lastIndexOf(","));
					}
					bo.set("TOID", toid);
				}

				if (bo.getString("FILECC") != null) {
					String ccid = "";
					String fileCCStr = bo.getString("FILECC");
					if (StringUtils.isNotEmpty(fileCCStr)) {
						String[] fileCCs = fileCCStr.split(",");
						if (fileCCs != null && fileCCs.length > 0) {
							for (String fileCC : fileCCs) {
								if (StringUtils.isNotEmpty(fileCC)) {
									// 根据团队ID查询团队名称
									TeamModel team = TeamCache.getModel(fileCC);
									if (team != null
											&& StringUtils.isNotEmpty(team
													.getName())) {
										ccid = ccid + team.getName() + ",";
									}
								}
							}
						}
					}
					if (StringUtils.isNotEmpty(ccid)) {
						ccid = ccid.substring(0, ccid.lastIndexOf(","));
					}
					bo.set("CCID", ccid);
				}
				SDK.getBOAPI().update(boName, bo);
			}
		}
	}

}
